package JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

import static cn.hutool.json.JSONUtil.toBean;

public class HutoolTest {
    @Test
    public void test01() {
        /*
          利用hutool
        *   JSONUtil  转换格式
                toJsonStr()  所有类型的java对象转换为json格式
                toJsonPrettyStr()  java对象转换为json格式,并格式化
                toBean()  json格式转换为java对象
                jsonStr.parseArray().toList(E)   解析数组形式的JSON字符串,并转换为指定类型的List集合
        *
        * */
        Student student = new Student("张三", 18, "男");
        String jsonStr = JSONUtil.toJsonStr(student);
        Student jsonObject = JSONUtil.toBean(jsonStr, Student.class);
//        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        System.out.println(jsonStr);
        System.out.println(jsonObject);
    }
    @Test
    public void test02() {
        String jsonStr = "{\"name\":\"张三\",\"age\":18,\"gender\":\"男\"}";
        Student jsonObject = JSONUtil.toBean(jsonStr, Student.class);
        System.out.println(jsonObject);
}
    @Test
    public void test03() {
        String jsonStr = "[{\"name\":\"张三\",\"age\":18,\"gender\":\"男\"},{\"name\":\"李四\",\"age\":19,\"gender\":\"女\"}]";
         JSONUtil.parseArray(jsonStr).toList(Student.class).forEach(System.out::println);

    }
    @Test
    public void test04() {
        Student[] students = {
                new Student("张三", 18, "男"),
                new Student("李四", 19, "女"),
                new Student("王五", 20, "男")
        };
        String jsonStr = JSONUtil.toJsonStr(students);
        System.out.println(jsonStr);
    }
    @Test
    public void test05() {
        Student[] students = {
                new Student("张三", 18, "男"),
                new Student("李四", 19, "女"),
                new Student("王五", 20, "男")
        };
        List<Student> list = Arrays.asList(students);
        String jsonStr = JSONUtil.toJsonStr(list);
        System.out.println(jsonStr);
    }
}
